//
//  YMNetLib.m
//  MyProject
//
//  Created by Pei on 16/6/19.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//

#import "YMNetLib.h"
#import "YMNetDataUtil.h"
#import "AFHTTPSessionManager.h"
#import "Reachability.h"
#import "YMUIUtil.h"
#import "YMUtil.h"
#import "UserInfo.h"

@interface YMNetLib ()
{
    NSDictionary *jsonDict;
}

@end

@implementation YMNetLib

@synthesize hostReachable;
@synthesize delegate;

SYNTHESIZE_SINGLETON_FOR_CLASS(YMNetLib);

- (id)init
{
    self = [super init];
    
    if (self)
    {
        self.hostReachable = NO;
    }
    
    return self;
}

- (void)connectWithAction:(NSString *)action method:(NSString*)method withContent:(NSString*)content withBody:(NSDictionary*)body withDelegate:(id)del
{
    [[YMUIUtil getInstance] hideLoadingView];
    [[YMUIUtil getInstance] showLoadingWithTitle:@"加载中..."];
    
    self.delegate = del;
    
    //NSString *commonStr = [YMNetDataUtil formateSysHeadWithAction];
    //NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",kAppApi(action),content,commonStr];
    //NSLog(@"urlStrurlStrurlStr%@", urlStr);
    //urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            break;
    }
    if (!isExistenceNetwork)
    {
        UIAlertView *_alertView =  [[UIAlertView alloc] initWithTitle:@"网络提示" message:@"无网络连接" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:/*@"联系客服",*/ nil];
        
        [_alertView show];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
    [manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    if ([method isEqualToString:@"POST"])
    {
        //NSDictionary *headerDic = [YMNetDataUtil formateDicSysHeadWithAction];
        NSString *urlStr = [NSString stringWithFormat:@"%@",kAppApi(action)];
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"url =  %@", urlStr);
        NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithDictionary:body];
        
        //NSData *dataFriends = [NSJSONSerialization dataWithJSONObject:tempDic options:NSJSONWritingPrettyPrinted error:nil];
        //NSString *jsonString = [[NSString alloc] initWithData:dataFriends encoding:NSUTF8StringEncoding];
        
        
        //[tempDic addEntriesFromDictionary:headerDic];
        NSLog(@"bodybodybody====%@", [tempDic description]);
        
        //manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //[manager POST:urlStr parameters:jsonString progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [manager POST:urlStr parameters:tempDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            jsonDict = [YMUtil changeType:(NSDictionary*)responseObject];
            NSLog(@"获取到的数据为：%@",jsonDict);
            [self.delegate NetDoOverSuccess:jsonDict];
            [[YMUIUtil getInstance] hideLoadingView];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            jsonDict = @{@"error":error};
            NSLog(@"发生错误！%@",error);
            [[YMUIUtil getInstance] hideLoadingView];
            if ([self.delegate respondsToSelector:@selector(NetDoOverFaild:)])
            {
                [self.delegate NetDoOverFaild:jsonDict];
            }
        }];
    }
    else if ([method isEqualToString:@"GET"])
    {
        NSString *commonStr = @"";//[YMNetDataUtil formateSysHeadWithAction];
        NSString *urlStr = nil;
        if (content == nil){
            urlStr = [NSString stringWithFormat:@"%@%@",kAppApi(action),commonStr];
        }else{
            urlStr = [NSString stringWithFormat:@"%@%@%@",kAppApi(action),content,commonStr];
        }


        NSLog(@"url = %@", urlStr);
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            jsonDict = [YMUtil changeType:(NSDictionary*)responseObject];
            NSLog(@"获取到的数据为：%@",jsonDict);
            [self.delegate NetDoOverSuccess:jsonDict];
            [[YMUIUtil getInstance] hideLoadingView];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            jsonDict = @{@"error":error};
            NSLog(@"发生错误！%@",error);
            [[YMUIUtil getInstance] hideLoadingView];
            if ([self.delegate respondsToSelector:@selector(NetDoOverFaild:)])
            {
                [self.delegate NetDoOverFaild:jsonDict];
            }
        }];
    }
    else if ([method isEqualToString:@"PUT"])
    {
        NSDictionary *headerDic = [YMNetDataUtil formateDicSysHeadWithAction];
        NSString *urlStr = [NSString stringWithFormat:@"%@",kAppApi(action)];
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"urlStr = %@",urlStr);
        NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithDictionary:body];
        [tempDic addEntriesFromDictionary:headerDic];
        
        [manager PUT:urlStr parameters:tempDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            jsonDict = [YMUtil changeType:(NSDictionary*)responseObject];
            
            NSLog(@"获取到的数据为：%@",jsonDict);
            [self.delegate NetDoOverSuccess:jsonDict];
            [[YMUIUtil getInstance] hideLoadingView];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            jsonDict = @{@"error":error};
            NSLog(@"发生错误！%@",error);
            [[YMUIUtil getInstance] hideLoadingView];
            if ([self.delegate respondsToSelector:@selector(NetDoOverFaild:)])
            {
                [self.delegate NetDoOverFaild:jsonDict];
            }
        }];
    }
    else if ([method isEqualToString:@"DELETE"])
    {
        NSString *commonStr = [YMNetDataUtil formateSysHeadWithAction];
        NSString *urlStr = nil;
        if (content == nil){
            urlStr = [NSString stringWithFormat:@"%@%@",kAppApi(action),commonStr];
        }else{
            urlStr = [NSString stringWithFormat:@"%@%@%@",kAppApi(action),content,commonStr];
        }
        NSLog(@"urlStrurlStrurlStr%@", urlStr);
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        [manager DELETE:urlStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            jsonDict = [YMUtil changeType:(NSDictionary*)responseObject];
            
            NSLog(@"获取到的数据为：%@",jsonDict);
            [self.delegate NetDoOverSuccess:jsonDict];
            [[YMUIUtil getInstance] hideLoadingView];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            jsonDict = @{@"error":error};
            NSLog(@"发生错误！%@",error);
            [[YMUIUtil getInstance] hideLoadingView];
            if ([self.delegate respondsToSelector:@selector(NetDoOverFaild:)])
            {
                [self.delegate NetDoOverFaild:jsonDict];
            }
        }];
    }
}

@end
